import Vue from "vue";
import VueRouter from "vue-router";
import routes from "@/router/routes";
import store from "@/store";
Vue.use(VueRouter);

let oringinPush = VueRouter.prototype.push;
let oringinReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    oringinPush.call(this, location, resolve, reject);
  } else {
    oringinPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    oringinReplace.call(this, location, resolve, reject);
  } else {
    oringinReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到顶部
    return { y: 0 };
  },
});
//全局导航守卫（前置）
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token;
  let name = store.state.user.userInfo.name;
  if (token) {
    //如果用户已经登录
    if (to.path == "/login"||to.path=='/register') {
      //已经登录且想去登录注册页（不能去，跳转到默认页即home页）
      next("/");
    } else {
      //已经登录且去的不是登录页，则进行判断
      if (name) {
        //如果用户信息已经拿到，则允许跳转
        next(); 
      } else {
        try {
          //否则派发请求拿到用户信息，再跳转
          await store.dispatch("getUserInfo"); 
          next();
        } catch (error) {
          //如果token过期了，无法拿到用户信息，则退出登录，返回登录页
          await store.dispatch("userLogOut"); 
          next("/login");
        }
      }
    }
  } else {
    //如果未登录，不允许去支付相关（pay,paysuccess,trade）,个人中心center,跳到登录页
    let topath=to.path
    if(topath.indexOf('/pay')!==-1 || topath.indexOf('/trade')!==-1 || topath.indexOf('/center')!==-1){
      //携带query参数redirect,记录用户登录前想去的路由路径，传给登录页
      next('/login?redirect='+topath)
    }else{
      next()
    }
  }
});

export default router;
